<?php

namespace App\Repository\Repositories;

use App\Http\Controllers\Controller;
use App\Http\Serve\Es;
use App\Models\StoreCoupon;
use App\Models\StoreCouponIssue;
use App\Models\StoreCouponIssueUser;
use App\Models\StoreProduct;
use App\Repository\RepositoryInterface\CouponInterface;
use Illuminate\Support\Facades\DB;

class CouponRepositories extends Controller implements CouponInterface
{
    protected $storeCoupon;
    public function __construct(StoreCoupon $storeCoupon)
    {
        $this->storeCoupon = $storeCoupon;
    }


    public function goodsDiscount()
    {
        try {
            $data = DB::table('store_coupon')->join('store_coupon_issue', 'store_coupon_issue.cid', 'store_coupon.id')
                ->where('store_coupon.is_del', 0)->where('store_coupon.status', 1)->where('start_time', '<', time())->where('store_coupon_issue.end_time', '>', time())->get()->toArray();
            return parent::success('success', $data);
        } catch (\Exception $exception) {
            return parent::error($exception->getMessage());
        }
    }

    /**
     * 添加数据
     * @param $data
     * @return \Illuminate\Http\JsonResponse
     */
    public function add($data)
    {
        try {
            $getId = StoreCoupon::create($data['one']);
            $data['two']['cid'] = $getId;
            $discountData = StoreCouponIssue::create($data['two']);

            if ($discountData) {
                $esData = StoreCoupon::readStoreCouponRead($getId)->toArray();
                $es = new Es();
                if (!$es->exists_index('discount')) {
                    $es->create_index('discount');
                }
                $es->add_doc($getId, $esData, 'discount', '_doc');
            }
            return parent::success('添加成功');
        } catch (\Exception $exception) {
            return parent::error($exception->getMessage());
        }
    }

    /**
     * 优惠券修改
     * @param $discountData
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function modification($discountData, $id)
    {
        try {
            unset($discountData['get_store_coupon']);
            unset($discountData['updated_at']);
            $updateRes = StoreCoupon::modification($discountData, $id);
            if ($updateRes) {
                $es = new Es();
                if (!$es->exists_index('discount')) {
                    $es->create_index('discount');
                }
                // 修改es的数据
                $es->update_doc($id, 'discount', '_doc', ['doc' => $discountData]);
            }
            return parent::success('修改成功', $discountData);
        } catch (\Exception $exception) {
            return parent::error($exception->getMessage());
        }
    }

    /**
     * 优惠券列表
     * @param $where
     * @return \Illuminate\Http\JsonResponse
     */
    public function listview($where)
    {
        try {
            $discountData = StoreCoupon::search($where);

            return parent::success('success', $discountData);
        } catch (\Exception $exception) {
            return parent::error($exception->getMessage());
        }
    }

    /**
     * es搜索
     * @param $search
     * @return bool|\Illuminate\Http\JsonResponse
     */
    public function esSearch($search)
    {
        if (!empty($search)) {
            $es = new Es();
            $body = [
                'query' => [
                    'match' => [
                        'title' => [
                            'query' => $search
                        ]
                    ]
                ],
                'highlight' => [
                    'fields' => [
                        'title' => [
                            'pre_tags' => [
                                '<span style="color: red">'
                            ],
                            'post_tags' => [
                                '</span>'
                            ]
                        ]
                    ]
                ]
            ];
            $res = $es->search_doc('discount', '_doc', $body);
            $data = array_column($res['hits']['hits'], '_source');
            foreach ($data as $key => &$v) {
                $v['title'] = $res['hits']['hits'][$key]['highlight']['title'][0];
            }
            unset($v);
            $data = ['data' => $data];
            return parent::success('success', $data);
        }
        return true;
    }

    /**
     * 优惠券删除
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function delete($id)
    {
        try {
            if (!is_numeric($id)) {
                throw new \ErrorException('删除优惠券参数错误');
            }
            $deleteRes = StoreCoupon::discountDeleted($id);
            if ($deleteRes) {
                $es = new Es();
                $es->delete_doc($id, 'discount', '_doc');
                StoreCouponIssue::discountDeleted($id);
            }
            return parent::success('success');
        } catch (\Exception $exception) {
            return parent::error($exception->getMessage());
        }
    }

    /**
     * 优惠券详情信息
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function read($id)
    {
        try {
            if (!is_numeric($id)) {
                throw new \ErrorException('删除优惠券参数错误');
            }
            $discountData = StoreCoupon::readStoreCouponRead($id);
            return parent::success('success', $discountData);
        } catch (\Exception $exception) {
            return parent::error($exception->getMessage());
        }
    }

    /**
     * 优惠券附表修改信息
     * @param $attachedData
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function attachedUpdate($attachedData, $id)
    {
        try {
            StoreCouponIssue::modification($attachedData, $id);
            return parent::success('修改成功');
        } catch (\Exception $exception) {
            return parent::error($exception->getMessage());
        }
    }

    /**
     * 查询个人优惠券
     * @param $id
     * @param $status
     * @return \Illuminate\Http\JsonResponse
     */
    public function userList($id, $status)
    {
        try {
            $userData = StoreCouponIssueUser::userStoreIssue($id, $status);
            return parent::success('success', $userData);
        } catch (\Exception $exception) {
            return parent::error($exception->getMessage());
        }
    }

    /**
     * 用户获取优惠券
     * @param $id
     * @param $couponId
     * @return \Illuminate\Http\JsonResponse
     */
    public function useradd($id, $couponId)
    {
        try {
            if (!is_numeric($id) || !is_numeric($couponId)) {
                throw new \ErrorException('参数不正确');
            }
            $couponData = StoreCoupon::readStoreCouponRead($couponId)->toArray();
            if ($couponData['get_store_coupon']['is_permanent'] == 1) {
                StoreCouponIssueUser::useradd($id, $couponId);
            } else {
                if ($couponData['get_store_coupon']['remain_count'] - 1 <= 0) {
                    throw new \ErrorException('优惠卷为空');
                } else {
                    StoreCouponIssueUser::useradd($id, $couponId);
                    $count = --$couponData['get_store_coupon']['remain_count'];
                    StoreCouponIssue::discountSubtract($id, $count);
                }
            }
            return parent::success('success');
        } catch (\ErrorException $exception) {
            return parent::error($exception->getMessage());
        }
    }

    /**
     * 优惠券的状态
     * @param $id
     * @param $status
     * @return \Illuminate\Http\JsonResponse
     */
    public function changeStatus($id, $status)
    {
        $status = StoreCoupon::changeStatus($id, $status);
        return parent::success($status);
    }

    /**
     * 获取商品信息
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGoods()
    {
        $goods = StoreProduct::all();
        return parent::success('success', $goods);
    }

    /**
     * 优惠券的状态
     * @param $uid
     * @param $data
     * @return \Illuminate\Http\JsonResponse
     */
    public function checkStatus($uid, $data)
    {
        try {
            DB::beginTransaction();
            foreach ($data as $v) {
                StoreCouponIssueUser::userCheckStatus($uid, $v);
            }
            DB::commit();
            return parent::success('success');
        } catch (\Exception $exception) {
            DB::rollBack();
            return parent::error('error');
        }
    }

    /**
     * 根据商品获取优惠券
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function productDiscount($id)
    {
        try {
            if (!is_numeric($id) || $id <= 0) {
                return parent::error('参数不正确');
            }
            $data = DB::table('store_coupon')->join('store_coupon_issue', 'store_coupon_issue.cid', 'store_coupon.id')
                ->where('store_coupon.is_del', 0)->where('store_coupon.status', 1)->where('start_time', '<', time())->where('store_coupon_issue.end_time', '>', time())->where('store_coupon_issue.remain_count', '>', '0')->get()->toArray();
            return parent::success('success', $data);
        } catch (\Exception $exception) {
            return parent::error("error");
        }

    }

    /**
     * 用户根据商品选择可用优惠卷
     * @param $uid
     * @param $goodsId
     * @return \Illuminate\Http\JsonResponse
     */
    public function goodsChange($uid, $goodsId)
    {
        try {
            $data = DB::table('store_coupon_issue_user')->join('store_coupon', 'store_coupon_issue_user.issue_coupon_id', 'store_coupon.id')
                ->where('store_coupon_issue_user.status', 0)->where('store_coupon.status', 1)->where('store_coupon.is_del', 0)->where('store_coupon.product_id', $goodsId)->get()->toArray();
            return parent::success("success", $data);
        } catch (\Exception $exception) {
            return parent::error("error");
        }
    }

    /**
     * wf
     * 个人优惠价
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function userCoupon($id)
    {

        try {
            $userData = StoreCouponIssueUser::userCoupon($id);
            foreach ($userData as $k => &$v){
                $coupon_time = $v['get_discount_data']['coupon_time'];
                $v['get_discount_data']['coupon_time'] = date('Y-m-d H:i:s',strtotime("+$coupon_time day",$v['add_time']));
            }
            return parent::success('success', $userData);
        } catch (\Exception $exception) {
            return parent::error($exception->getMessage());
        }
    }
    /**
     * wf
     * 查询个人已使用/未使用/已过期优惠券
     * @param $id
     * @param $status
     * @return \Illuminate\Http\JsonResponse
     */
    public function myList($id, $status)
    {
        try {
            $userData = StoreCouponIssueUser::userStoreIssue($id, $status);
            foreach ($userData as $k => &$v){
                $coupon_time = $v['get_discount_data']['coupon_time'];
                $v['get_discount_data']['coupon_time'] = date('Y-m-d H:i:s',strtotime("+$coupon_time day",$v['add_time']));
            }
            return parent::success('success', $userData);
        } catch (\Exception $exception) {
            return parent::error($exception->getMessage());
        }
    }

}
